{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
    .gift-box .layui-form{padding: 0!important;}
    .exchange-coupon, .exchange-red-packet {display: none;}
    .form-wrap{margin-top: 0;}
	.exchange-type {padding: 0 20px; position: relative;}
	.exchange-type i{position: absolute;bottom: -10px;right: -1px;display: none;}
    .exchange-type.border-color i{display: block;}

	.layui-input {display: inline-block;}
	.text-empty {color: #454545;}
	.js-coupon-discount{display: none;}
	.layui-table-body{max-height: 480px !important;}
	.gift-box .layui-table-body{max-height: 350px !important;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
	.prompt-block .prompt-box{
		top:unset;bottom:30px;left:-85px;
	}
	.layui-table-cell{overflow:inherit;}
	.layui-table-box{overflow:inherit;}
	.layui-table-header{overflow:inherit;}
	.prompt-block .prompt-box:before{
		transform:rotate(-90deg);left:84px;top:104px;
	}
	.prompt-block .prompt-box:after{
		transform:rotate(-90deg);left:84px;top:103px;
	}
	.delivery_model{width:20%;display: inline-block;}
	.layui-input-block{margin-bottom:16px;}
	.print.delivery_model .layui-anim-upbit{z-index:1000}
	.goods_num {padding-left: 20px;}
</style>
{/block}
{block name="main"}
<div class="form-wrap">
	<div class="layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label">兑换类型：</label>
			<div class="layui-input-block">
				<button class="layui-btn layui-btn-primary exchange-type  border-color" id="gift_btn">商品<i class="iconfont iconxuanzhong text-color"></i></button>
				<button class="layui-btn layui-btn-primary exchange-type" id="coupon_btn">优惠券<i class="iconfont iconxuanzhong text-color"></i></button>
				<button class="layui-btn layui-btn-primary exchange-type" id="red_packet_btn">红包<i class="iconfont iconxuanzhong text-color"></i></button>
			</div>
		</div>
	</div>

	<!-- 商品 -->
	<div class="exchange-gift layui-form content">

		<div class="layui-form-item">
			<label class="layui-form-label">是否上架：</label>
			<div class="layui-input-block">
				<input type="checkbox" name="state" lay-skin="switch" value="1" lay-filter="state" checked>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">是否免邮：</label>
			<div class="layui-input-block">
				<input type="checkbox" name="is_free_shipping"  value="1" lay-filter="shipping" checked class="shipping" lay-skin="switch">
			</div>
		</div>

		<div class="layui-form-item ems_block" style="display:none;padding-left:100px;">
			<div class="layui-input-block">
				<input type="checkbox" name="delivery_type" title="按照商品设置" lay-skin="primary" lay-filter="delivery_type" class="delivery_type" value="2">
				<div class="word-aux" style="margin-left: 28px;margin-top: 0">
					<p>如果选择按照商品设置,那么积分商城商品将会根据商品中设置的运费模版进行</p>
					<p>计算运费</p>
				</div>
			</div>
			<div class="layui-input-block">
				<input type="checkbox" name="delivery_type" title="固定运费" lay-skin="primary" lay-filter="delivery_type" class="delivery_type" value="0">
				<input class="layui-input len-short print" type="number" style="display:none;" name="delivery_price" onblur="checkInput(this)">
				<div class="word-aux" style="margin-left: 28px;margin-top: 0">
					<p>如果选择固定运费,积分商城的商品无论购买几件,将会按照设置的固定运费收取,</p>
					<p>如:固定运费设置为12元,客户兑换A商品时无论一次兑换几件,运费都是12元.</p>
				</div>
			</div>
			<div class="layui-input-block">
				<input type="checkbox" name="delivery_type" title="运费模版" lay-skin="primary" lay-filter="delivery_type" class="delivery_type layui-form-label" value="1">
				<div class="print delivery_model" style="display:none;">
					<select name="shipping_template" lay-filter="delivery_model">
						<option value="0">请选择运费模版</option>
						{foreach name="$express_template_list" item="vo"}
						<option value="{$vo['template_id']}">{$vo['template_name']}</option>
						{/foreach}
					</select>
				</div>
				<div class="word-aux" style="margin-left: 28px;margin-top: 0">
					<p>如果选择运费模版,积分商城的商品将会按照该处选择的运费模版进行单独计算</p>
					<p>运费,与商品本身设置的是否包邮以及运费模版无关.</p>
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">兑换规则：</label>
			<div class="layui-input-block special-length">
				<script id="containerG" name="containerG" type="text/plain" style="width:100%;height:500px;"></script>
			</div>
		</div>
		
		<div class="layui-form-item goods_list">
			<label class="layui-form-label"><span class="required">*</span>商品选择：</label>
			<div class="layui-input-block layui-form">
				<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
				<button class="layui-btn" onclick="addGoods()">选择商品</button> <span class="goods_num">已选商品（<span id="goods_num" class="text-color">0</span>）</span>
			</div>
		</div>
		<div class="form-row">
			<button class="layui-btn" lay-submit lay-filter="save_gift">保存</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>

		<input type="hidden" name="sku_id">
		<input type="hidden" name="type" value="1">
	</div>

	<!-- 优惠券 -->
	<div class="exchange-coupon content layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>选择优惠券：</label>
			<div class="layui-input-block">
				<div class="upload-img-block square">
					<div class="upload-img-box upload-coupon" id="coupon_img" lay-verify="select">
						<div class="upload-default">
							<i class="iconfont iconshangchuan"></i>
							<p>选择优惠券</p>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">优惠券名称：</label>
			<div class="layui-input-block" id="coupon_name">
				<p class="input-text text-empty">优惠券名称</p>
			</div>
		</div>

		<div class="layui-form-item js-coupon-price">
			<label class="layui-form-label">优惠券面值（元）：</label>
			<div class="layui-input-block" id="coupon_price">
				<p class="input-text text-empty">￥0.00</p>
			</div>
		</div>

		<div class="layui-form-item js-coupon-discount">
			<label class="layui-form-label">优惠券折扣：</label>
			<div class="layui-input-block" id="coupon_discount">
				<p class="input-text text-empty">0.00折</p>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>兑换积分：</label>
			<div class="layui-input-block">
				<input type="number" name="point" min="0" lay-verify="required|required_point" placeholder="兑换积分数" value="0" onchange="detectionNumType(this,'integral')" class="layui-input len-short expoint">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>可兑换数量：</label>
			<div class="layui-input-block">
				<input type="number" name="stock" min="0" lay-verify="required|required_coupon_stock" placeholder="可兑换数量" value="" onchange="detectionNumType(this,'integral')" class="layui-input len-short stock">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">是否上架：</label>
			<div class="layui-input-block">
				<input type="checkbox" name="state" lay-skin="switch" value="1" lay-filter="state" checked>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">兑换规则：</label>
			<div class="layui-input-block special-length">
				<script id="container" name="content" type="text/plain" style="width: 800px; height: 300px;"></script>
			</div>
		</div>

		<div class="form-row">
			<button class="layui-btn" lay-submit lay-filter="save_coupon">保存</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>

		<input type="hidden" name="coupon_type_id">
		<input type="hidden" name="type" value="2">
	</div>

	<!-- 红包 -->
	<div class="exchange-red-packet content layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>名称：</label>
			<div class="layui-input-block">
				<input type="text" name="name" lay-verify="required" placeholder="请输入红包名称" value="" class="layui-input len-long">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">红包封面：</label>
			<div class="layui-input-inline img-upload">
				<div class="upload-img-block icon square">
					<div class="upload-img-box" >
						<div class="upload-default" id="redPacket">
							<div class="upload">
								<i class="iconfont iconshangchuan"></i>
								<p>点击上传</p>
							</div>
						</div>
						<div class="operation">
							<div>
								<i title="图片预览" class="iconfont iconreview js-preview" style="margin-right: 20px;"></i>
								<i title="删除图片" class="layui-icon layui-icon-delete js-delete"></i>
							</div>
							<div class="replace_img js-replace">点击替换</div>
						</div>
						<input type="hidden" name="image" />
					</div>
					<!-- <p id="redPacket" class="no-replace">替换</p>
					<input type="hidden" name="image" />
					<i class="del">x</i> -->
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>兑换积分：</label>
			<div class="layui-input-block">
				<input type="number" name="point" min="0" lay-verify="required|required_point" placeholder="兑换积分数" value="0" onchange="detectionNumType(this,'integral')" class="layui-input len-short expoint">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>可兑换数量：</label>
			<div class="layui-input-block">
				<input type="number" name="stock" min="0" lay-verify="required|required_balance_stock" placeholder="可兑换数量" value="" onchange="detectionNumType(this,'integral')" class="layui-input len-short stock">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>余额：</label>
			<div class="layui-input-block">
				<input type="number" name="balance" min="0" lay-verify="required|required_balance" placeholder="红包余额" value="" onchange="detectionNumType(this,'positiveNumber')" class="layui-input len-short">
			</div>
			<p class="word-aux">兑换的红包会以余额的形式发放给指定会员</p>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">是否上架：</label>
			<div class="layui-input-block">
				<input type="checkbox" name="state" lay-skin="switch" value="1" lay-filter="state" checked>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">兑换规则：</label>
			<div class="layui-input-block special-length">
				<script id="containerT" name="content" type="text/plain" style="width: 800px; height: 300px;"></script>
			</div>
		</div>

		<div class="form-row">
			<button class="layui-btn" lay-submit lay-filter="save">保存</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>
		<input type="hidden" name="type" value="3">
		<input type="hidden" name="" id="redPacketContent" value="" />
	</div>
</div>
<a id="redPacketImage"></a>
{/block}
{block name="script"}
<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="change-number">兑换次数</button>
	<button class="layui-btn layui-btn-primary" lay-event="goods-integral">所需积分</button>
	<button class="layui-btn layui-btn-primary" lay-event="goods-price">所需金额</button>
</script>

<!-- 优惠券 -->
<script type="text/html" id="couponList">
	<div class="gift-box">
		<div class="single-filter-box">
			<div class="layui-form">
				<div class="layui-input-inline">
					<input type="text" name="coupon_name" placeholder="请输入优惠券名称" class="layui-input len-mid">
					<button type="button" class="layui-btn layui-btn-primary" lay-filter="coupon-search" lay-submit>
						<i class="layui-icon">&#xe615;</i>
					</button>
				</div>
			</div>
		</div>
		<table id="coupon_list" lay-filter="coupon_list"></table>
	</div>
</script>

<!-- 优惠券-名称 -->
<script type="text/html" id="couponName">
	<div class="table-tuwen-box">
		<div class="img-box">
			{{#  if(d.image){  }}
			<img layer-src src="{{ns.img(d.image.split(',')[0])}}" alt="">
			{{# }else{  }}
			<img layer-src src="__STATIC__/img/coupon_default.png"/>
			{{#  }  }}
		</div>
		<div class="font-box">
			<p class="multi-line-hiding">{{d.coupon_name}}</p>
		</div>
	</div>
</script>

<!-- 优惠券-操作 -->
<script type="text/html" id="couponOperation">
	{{# if(d.is_exit == 1){ }}
	<p title="该优惠券已参加积分兑换活动">已添加</p>
	{{# }else{ }}
	<a class="layui-btn" lay-event="add">添加</a>
	{{# } }}
</script>

<!-- 商品操作 -->
<script type="text/html" id="operation">
	<div class="table-btn">
		<a class="layui-btn" onclick="delGoods(this,{{d.sku_id}})">删除</a>
	</div>
</script>

<script type="text/html" id="exchangePoint">
	<input type="number" class="layui-input len-input exchange_point expoint" onchange="setSkulist('point', {{d.sku_id}}, this , 'integral')" value="{{d.point ? d.point : 0.00}}" lay-verify="exchange_point" min="0.00"/>
</script>

<script type="text/html" id="exchangeLimit">
	<input type="number" class="layui-input len-input exchange_limit_num expoint" onchange="setSkulist('limit_num', {{d.sku_id}}, this, 'integral')" value="{{d.limit_num ? d.limit_num : 0}}" lay-verify="exchange_point" min="0.00"/>
</script>

<script type="text/html" id="exchangeMoney">
	<input type="number" class="layui-input len-input exchange_money"  value="{{d.exchange_price ? d.exchange_price : 0.00}}" lay-verify="exchange_money" min="0.00" onchange="setSkulist('exchange_price', {{d.sku_id}}, this, 'positiveNumber')"/>
</script>

<script type="text/html" id="ems_price">
	<div>
		<input type="checkbox"  name="delivery_type" lay-filter="is_set_ems" data-id="{{d.sku_id}}" onclick="setSkulist('delivery_type', {{d.sku_id}}, this, 'integral')" lay-skin="primary" checked>单独设置
		<input type="number" class="set_{{d.sku_id}} layui-input len-input" style="width:50%;margin-left:5%;" onchange="setSkulist('delivery_price', {{d.sku_id}}, this, 'integral')" value="0">
	</div>
</script>

<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/lang/zh-cn/zh-cn.js"></script>

<script>
	var giftTable, couponTable, form, laytpl,
        selectGoodsSkuId = [],
        exchangeType = 1;
	var goods_id = [], selectedGoodsId = [], sku_list = [];
	var saveData = null;
	var totalUploadNum = 0;
	var completeUploadNum = 0;

    //实例化富文本
    var ue = UE.getEditor('container'),
        ue_t = UE.getEditor('containerT'),
		ue_g = UE.getEditor('containerG'),
        html = '';

	// 已经添加的兑换列表
	var gift_list = [];
	var coupon_list = [];
	$.ajax({
		url: ns.url("pointexchange://shop/exchange/lists"),
		dataType: 'JSON',
		type: 'POST',
		async: false,
		success: function(res) {

			var data = res.data.list;
			for (var i=0; i<data.length; i++) {
				if (data[i].type == 1) {
					gift_list.push(data[i].type_id);
				}
				if (data[i].type == 2) {
					coupon_list.push(data[i].type_id);
				}
			}
		}
	});

    layui.use(['form', 'laytpl'], function(){
        form = layui.form;
        laytpl = layui.laytpl;
		form.render();

        /* form.on('radio(exchange_type)', function(data){
            exchangeType = data.value;
            $(".content").addClass("display-none").eq(exchangeType - 1).removeClass("display-none");
        }); */

		renderTable(sku_list);

		$(".exchange-type").click(function() {
			$(this).addClass("border-color");
			$(this).siblings("button").removeClass("border-color");

			if ($(this).index() == 0) {
				$(".exchange-gift").show();
				$(".exchange-coupon").hide();
				$(".exchange-red-packet").hide();
			} else if ($(this).index() == 1) {
				$(".exchange-coupon").show();
				$(".exchange-gift").hide();
				$(".exchange-red-packet").hide();
			} else if ($(this).index() == 2) {
				$(".exchange-red-packet").show();
				$(".exchange-gift").hide();
				$(".exchange-coupon").hide();
			}
		});

		var upload = new Upload({
			elem: '#redPacket',
			auto:false,
			bindAction:'#redPacketImage',
			callback: function(res) {
				uploadComplete('image', res.data.pic_path);
			}
		});

        /**
         * 商品列表搜索
         */
        form.on('submit(gift-search)', function(data) {
            giftTable.reload({
                page: {
                    curr: 1
                },
                where: data.field
            });
        });

		form.on('switch(shipping)', function(data){
			if(data.elem.checked){
				$(".ems_block").hide();
			}else{
				$(".ems_block").show();
			}
		});

		//监听邮费设置
		form.on('checkbox(delivery_type)', function(data){
			if(data.elem.checked){
				$("input[name='delivery_type']").prop("checked", false);
				$(this).prop("checked", true);
				form.render('checkbox');
				$(this).siblings(".print").show();
				$(this).parent().siblings().children(".print").hide()
			}else{
				$(this).siblings(".print").hide();
			}
		});

        /**
         * 优惠券列表搜索
         */
        form.on('submit(coupon-search)', function(data) {
            couponTable.reload({
                page: {
                    curr: 1
                },
                where: data.field
            });
        });

        /**
         * 监听表单提交
         */
		form.on('submit(save_gift)', function(data) {
			if(goodsVerify()) {
				var sku_ids = [];
				var goods_data = [];

				$.each(sku_list, function (i, e) {
					var goods = {};
					goods.goods_id = e.goods_id;
					sku_ids.push(e.sku_id);
					if(goods_data.length == 0){
						goods_data.push(goods);
					}else {
						$.each(goods_data, function(index, event){
							if(goods_data.length == index+1 && event.goods_id != goods.goods_id){
								goods_data.push(goods);
							}
						})
					}
				});

				if (sku_ids.length == 0) {
					layer.msg('请选择兑换商品', {icon: 5, anim: 6});
					return;
				}

				$.each(goods_data, function (i, e) {
					goods_data[i]['sku_list'] = [];
					$.each(sku_list, function (index, event) {
						if(event.goods_id == e.goods_id) {
							goods_data[i]['sku_list'].push(event);
						}
					});
				});

				ue_g.ready(function() {   //对编辑器的操作最好在编辑器ready之后再做
					html = ue_g.getContent();   //获取html内容，返回: <p>hello</p>
				});

				data.field.content = html;

				data.field.goods_data = goods_data;

				if (data.field.state == undefined) {
					data.field.state = 0;
				}
				saveData = data;
				ajax_save();
			}
		});

		form.on('submit(save_coupon)', function(data) {
			var _val = $("input[name='coupon_type_id']").val();
			if (!_val) {
				layer.msg('请选择兑换优惠券', {icon: 5, anim: 6});
				return;
			}

			if (data.field.state == undefined) {
				data.field.state = 0;
			}

			ue.ready(function() {   //对编辑器的操作最好在编辑器ready之后再做
				html = ue.getContent();   //获取html内容，返回: <p>hello</p>
			});

		    data.field.content = html;
			saveData = data;
		    ajax_save();
		});

        form.on('submit(save)', function(data) {
			if (data.field.state == undefined) {
				data.field.state = 0;
			}

			ue_t.ready(function() {   //对编辑器的操作最好在编辑器ready之后再做
				html = ue_t.getContent();   //获取html内容，返回: <p>hello</p>
			});

            data.field.content = html;

			// 删除图片
			// if(!data.field.image) upload.delete();

			saveData = data;
			var obj = $("img.img_prev[data-prev='1']");
			totalUploadNum = obj.length;
			if(totalUploadNum > 0){
				obj.each(function(){
					var actionId = $(this).attr('data-action-id');
					$(actionId).click();
				})
			}else{
				ajax_save();
			}
        });

		function uploadComplete(field, pic_path) {
			saveData.field[field] = pic_path;
			completeUploadNum += 1;
			if(completeUploadNum == totalUploadNum){
				ajax_save();
			}
		}

        function goodsVerify(){
			for (var i in sku_list){
				if (parseFloat(sku_list[i]['point']) <= 0) {
					layer.msg('兑换积分不能小于等于0', {icon: 5, anim: 6});
					return false;
				}
			}
			return true;
		}

		function ajax_save() {
        	var data = saveData.field;
			// 删除图片
			if(!data.image) upload.delete();

			var type = $('.exchange-type .border-color').attr('id');
			if (type == 'gift_btn') {
				//不免邮
				if(data.is_free_shipping==undefined){
					data.is_free_shipping = 0;
				}
				if(data.is_free_shipping == 0 && data.type == 1){
					if(data.delivery_type==undefined){
						layer.msg('请选择运费类型', {icon: 5, anim: 6});
						return false;
					}else if(data.delivery_type==0){
						if(data.delivery_price==""){
							layer.msg('请填写固定邮费', {icon: 5, anim: 6});
							return false;
						}
					}else if(data.delivery_type==1){
						if(data.shipping_template<=0){
							layer.msg('请选择运费模版', {icon: 5, anim: 6});
							return false;
						}
					}
				}else{
					data.delivery_type = "";
					data.delivery_price = "";
					data.shipping_template = 0;
				}
			}

			$.ajax({
			    url: ns.url("pointexchange://shop/exchange/add"),
			    data: data,
			    dataType: 'JSON',
			    type: 'POST',
			    async: false,
			    success: function (res) {
			        if (res.code == 0) {
			            layer.confirm('添加成功', {
			                title:'操作提示',
			                btn: ['返回列表', '继续操作'],
							closeBtn: 0,
			                yes: function(){
			                    location.href = ns.url("pointexchange://shop/exchange/lists")
			                },
			                btn2: function() {
			                    location.reload();
			                }
			            });
			        } else {
			            layer.msg(res.message, {icon: 5, anim: 6});
			        }
			    }
			});
		}

        //监听兑换方式
        form.on('radio(pay_type)', function(data){
            var value = data.value;
            var html = '';
            if(value == 1){
                html = '<input type="number" name="point" min="0" lay-verify="required_point" autocomplete="off" class="layui-input len-short"> 积分' +
                    '&nbsp;&nbsp;+ &nbsp;&nbsp;<input type="number" name="price" min="0" lay-verify="required_money" autocomplete="off" class="layui-input len-short"> 元' +
                    '';
            }
            if(value == 0){
                html = '<input type="number" name="point" min="0"  lay-verify="required" autocomplete="off" class="layui-input len-short"> 积分';
            }
			$('.pay_price').html(html);
        });

		form.verify({
			required_point: function(value) {
				if (value == "") {
					return '积分不能为空';
				}
                if (Number(value) <= 0){
                    return '积分必须大于0！';
                }
			},
			required_money: function(value) {
				if (value == "") {
					return '金额不能为空';
				}
                if (Number(value) <= 0){
                    return '价格必须大于0！';
                }
			},
            required_limit: function(value) {
                if (Number(value) < 1){
                    return '兑换限制不能小于1！';
                }
            },
			required_coupon_stock: function(value) {
				if (Number(value) <= 0){
					return '可兑换数量必须大于0！';
				}
			},
            required_balance_stock: function(value) {
                if (Number(value) <= 0){
                    return '可兑换数量必须大于0！';
                }
            },
            required_balance: function(value) {
                if (Number(value) <= 0){
                    return '红包余额必须大于0！';
                }
            }
		})
    });

    /* 商品 */
    $("body").on("click", ".upload-gift",function () {

        goodsSelect(function (res) {
        	if(!res.length) return false;
			selectGoodsSkuId = [];
            var html = "", price = 0.00;
            for (var i = 0; i < res.length; i++) {
                for (var k = 0; k < res[i].selected_sku_list.length; k++) {
                    var item = res[i].selected_sku_list[k];

                    var img_path = ns.img(item.sku_image,'small');
                    $("#gift_name").html("<p class='input-text'>"+item.sku_name+"</p>");
                    if (item.sku_image != "") {
                        $("#gift_img").html('<img src="'+ img_path +'" />');
                    } else {
                        $("#gift_img").html("");
                    }
                    $("#gift_price").html("<p class='input-text'>￥<span class='sku_price'>"+item.price+"</span></p>");
                    $("#gift_stock").html("<p class='input-text'>"+item.stock+"</p>");
                    $(".select-gift-list tbody").html(html);
                    $("input[name=sku_id]").val(item.sku_id);

                    selectGoodsSkuId.push(item.sku_id);
                }
            }

            $("#goods tbody").html(html);
            $(".original-price").text(price);
            $(".combined-price").val(price);
            $(".save-prices").text(0);
        }, selectGoodsSkuId, {mode: "sku", max_num: 1, min_num: 1,disabled:0});

    });

    /* 优惠券 */
    $("body").on("click", ".upload-coupon",function () {
        layer.open({
            type: 1,
            area: ["900px","650px"],
            title: '优惠券列表',
            content: $("#couponList").html()
        });

        couponTable = new Table({
            elem: "#coupon_list",
            url: ns.url("pointexchange://shop/exchange/getCouponList"),
            where: {'status': 1},
            cols: [
                [{
					title: '优惠券名称',
					unresize: 'false',
					width: '20%',
					templet: '#couponName'
				}, {
					field: 'money',
					title: '优惠券面额（元）',
					unresize: 'false',
					width: '15%'
				}, {
					field: 'count',
					title: '发放数量',
					unresize: 'false',
					width: '15%',
                    templet: function(data){
						return data.count == -1 ? '无限制' : data.count;
					}
				}, {
					field: 'max_fetch',
					title: '最大领取数量',
					unresize: 'false',
					width: '15%',
					templet:function(data){
						return data.max_fetch == 0 ? '无限制' : data.max_fetch;
					}
				}, {
					field: 'gift_state',
					title: '有效期限',
					unresize: 'false',
					width: '25%',
					templet: function (res) {
						if(res.validity_type == 0){
							return "有效时间至" + ns.time_to_date(res.end_time);
						}else{
							return "有效时间" + res.fixed_term + "天";
						}
					}
				}, {
					title: '操作',
					toolbar: '#couponOperation',
					unresize: 'false',
					align:'right'
				}]
            ]
        });

        couponTable.tool(function(obj) {
            var data = obj.data;
            switch (obj.event) {
                case "add":
                    addcoupon(data);
                    break;
            }
        });

		function addcoupon(data){
            var img_path = ns.img(data.image);
            $("#coupon_name").html("<p class='input-text'>"+data.coupon_name+"</p>");
			if (data.image) {
				$("#coupon_img").html('<img src="'+ img_path +'" />');
			} else {
				$("#coupon_img").html('<img src="__STATIC__/img/coupon_default.png" />');
			}
			if(data.type == "reward"){
				$(".js-coupon-price").show();
				$(".js-coupon-discount").hide();
				$("#coupon_price").html("<p class='input-text'>￥"+data.money+"</p>");
			}else{
				$(".js-coupon-price").hide();
				$(".js-coupon-discount").show();
				$("#coupon_discount").html("<p class='input-text'>"+data.discount+"折</p>");
			}
            $("input[name=coupon_type_id]").val(data.coupon_type_id);
            layer.closeAll();
        }

    });

	function delGoods(obj,id) {
		var goods_ids = [];
		for (let i = 0; i < sku_list.length; i++){
			if (sku_list[i].sku_id == parseInt(id)){
				sku_list.splice(i,1);
			}
		}
		for (let i = 0; i < sku_list.length; i++){
			goods_ids.push(sku_list[i].goods_id);
		}
		$(obj).parents("tr").remove();
		$("#goods_num").html(sku_list.length);
		selectedGoodsId = goods_ids.toString();
	}

	// 表格渲染
	function renderTable(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page: false,
			limit: Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								 <p class="multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					align: 'left',
					width: '10%',
					templet: function(data) {
						return '<p class="line-hiding" title="'+ data.price +'">￥<span>' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '<span title="兑换次数(0为不限次)">兑换次数(0为不限次)</span>',
					unresize: 'false',
					width: '14%',
					templet: '#exchangeLimit'
				}, {
					title: '<span title="兑换所需积分">所需积分</span>',
					unresize: 'false',
					width: '12%',
					templet: '#exchangePoint'
				}, {
					title: '<span title="兑换所需金额">所需金额</span>',
					unresize: 'false',
					width: '12%',
					templet: '#exchangeMoney'
				},
				{
					title: '操作',
					toolbar: '#operation',
					unresize: 'false',
					align:'right'
				}]
			],
			callback:function(){
				form.render();
			},
			data: sku_list,
			toolbar: '#toolbarOperation'
		});

		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "change-number":
					editInput(0,obj);
					break;
				case "goods-integral":
					editInput(1,obj);
					break;
				case "goods-price":
					editInput(2,obj);
					break;
			}
		});
	}
	function editInput(textIndex=0,data) {
		var text = [{
			name: '兑换次数',
			value: 'limit_num'
		},{
			name: '所需积分',
			value: 'point'
		},{
			name: '所需金额',
			value: 'exchange_price'
		}];
		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" onchange="detectionNumType(this,'integral')" class="layui-input len-mid" placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					sku_list.forEach(function (skuItem,skuIndex) {
						if (item.sku_id == skuItem.sku_id){
							sku_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				renderTable(sku_list);
				layer.closeAll();
			}
		});
	}

	/* 商品 */
	function addGoods(){
		goodsSelect(function (res) {
			if (!res.length) return false;
			goods_id = [];
			sku_list = [];
			for(var i=0;i<res.length;i++) {
				for (var k = 0; k < res[i].selected_sku_list.length; k++) {
					var item = res[i].selected_sku_list[k];
					item.exchange_price = 0;
					item.point = 0;
					item.limit_num = 0;
					goods_id.push(item.goods_id);
					sku_list.push(item);
				}
			}
			renderTable(sku_list);
			selectedGoodsId = goods_id;
			$("#goods_num").html(sku_list.length)
		}, selectedGoodsId);
	}

	function setSkulist(type, sku_id, obj,num_type){
		var value = $(obj).val();
			//大于零 且 不是小数
			if (value < 0 && num_type == 'integral')
				$(obj).val(0);
			else if (num_type == 'integral')
				$(obj).val(Math.round(value));

			//大于1 且 不是小数
			if (value < 1 && num_type == 'positiveInteger')
				$(obj).val(1);
			else if (num_type == 'positiveInteger')
				$(obj).val(Math.round(value));
			//大于零可以是小数
			if (num_type == 'positiveNumber') {
				value = parseFloat(value).toFixed(2);
				if (value < 0)
					$(obj).val(0);
				else
					$(obj).val(value);
			}
		$.each(sku_list, function (i, e) {
			if(sku_id == e.sku_id){
				sku_list[i][type] = $(obj).val();
			}
		})
	}

    //返回
    function back() {
        location.href = ns.url("pointexchange://shop/exchange/lists");
    }
	$("body").on('keyup', '.stock', function() {
		var value = $(this).val();
		if(value % 1 !== 0){
			layer.msg("红包数量请输入整数");
			$(this).val(0);
		}
	});
	
	$("body").on('keyup', '.expoint', function() {
		var value = $(this).val() ;
		if(value % 1 !== 0){
			layer.msg("兑换积分请输入整数");
			$(this).val(0);
		}
	});

	//检测数据类型
	function detectionNumType(el, type) {
        var value = $(el).val();
        //大于零 且 不是小数
        if (value < 0 && type == 'integral')
            $(el).val(0);
        else if (type == 'integral')
            $(el).val(Math.round(value));

        //大于1 且 不是小数
        if (value < 1 && type == 'positiveInteger')
            $(el).val(1);
        else if (type == 'positiveInteger')
            $(el).val(Math.round(value));
        //大于零可以是小数
        if (type == 'positiveNumber') {
            value = parseFloat(value).toFixed(2);
            if (value < 0)
                $(el).val(0);
            else
                $(el).val(value);
        }
    }
	function checkInput(obj){
		$(obj).val(Math.abs($(obj).val()));
	}
</script>
{/block}